package com.linln.common.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	 /** 
     * 默认日期格式 
     */  
    public static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";  
    public static String SIMPLE_DATE_FORMAT = "yyyyMMdd";
    public static String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; 	  
	 /**
     * 格式化日期 
     * @param date 日期对象 
     * @return String 日期字符串 
     */  
    public static String formatDate(Date date){  
        SimpleDateFormat f = new SimpleDateFormat(DEFAULT_DATE_FORMAT);  
        String sDate = f.format(date);  
        return sDate;  
    } 
	/** 
     * 获取某年第一天日期 
     * @param year 年份 
     * @return Date 
     */  
    public static Date getCurrYearFirst(int year){  
        Calendar calendar = Calendar.getInstance();  
        calendar.clear();  
        calendar.set(Calendar.YEAR, year);  
        Date currYearFirst = calendar.getTime();  
        return currYearFirst;  
    }  
      
    /** 
     * 获取某年最后一天日期 
     * @param year 年份 
     * @return Date 
     */  
    public static Date getCurrYearLast(int year){  
        Calendar calendar = Calendar.getInstance();  
        calendar.clear();  
        calendar.set(Calendar.YEAR, year);  
        calendar.roll(Calendar.DAY_OF_YEAR, -1);  
        Date currYearLast = calendar.getTime();  
          
        return currYearLast;  
    } 
    
    /* 
	 * @param date1 <String>
	 * @param date2 <String>
	 * @return int
	 * @throws ParseException
	 */
	public static int getMonthSpace(String date1, String date2)
			throws ParseException {

		int result = 0;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();

		c1.setTime(sdf.parse(date1));
		c2.setTime(sdf.parse(date2));

		result = c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH);

		return result == 0 ? 1 : Math.abs(result);

	}
    /**
     *  获取前月的第一天
     * @param month
     * @return
     */
	public static int getCurrMonthFirst(int month){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
         
        //获取前月的第一天
        Calendar   cal_1=Calendar.getInstance();//获取当前日期 
        cal_1.add(Calendar.MONTH, -1);
        cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
        String strfirstDay = format.format(cal_1.getTime());
        int firstDay=Integer.parseInt(strfirstDay);
        return firstDay;

	}
	/**
     * 获取某月的最后一天
     * @Title:getLastDayOfMonth
     * @Description:
     * @param:@param year
     * @param:@param month
     * @param:@return
     * @return:String
     * @throws
     */
	public static String getLastDayOfMonth(int year,int month){
		 Calendar cal = Calendar.getInstance();
	        //设置年份
	        cal.set(Calendar.YEAR,year);
	        //设置月份
	        cal.set(Calendar.MONTH, month-1);
	        //获取某月最大天数
	        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
	        //设置日历中月份的最大天数
	        cal.set(Calendar.DAY_OF_MONTH, lastDay);
	        //格式化日期
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	        String lastDayOfMonth = sdf.format(cal.getTime());
	         
	        return lastDayOfMonth;


	}
	/**
     * 计算年龄
     * @Title:getAge
     * @Description:
     * @param:@param birthDay
     * @throws
     */
	public static int getAge(Date birthDay) throws Exception { 
        Calendar cal = Calendar.getInstance(); 

        if (cal.before(birthDay)) { 
            throw new IllegalArgumentException( 
                "The birthDay is before Now.It's unbelievable!"); 
        } 

        int yearNow = cal.get(Calendar.YEAR); 
        int monthNow = cal.get(Calendar.MONTH)+1; 
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); 
        
        cal.setTime(birthDay); 
        int yearBirth = cal.get(Calendar.YEAR); 
        int monthBirth = cal.get(Calendar.MONTH); 
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); 

        int age = yearNow - yearBirth; 

        if (monthNow <= monthBirth) { 
            if (monthNow == monthBirth) { 
                //monthNow==monthBirth 
                if (dayOfMonthNow < dayOfMonthBirth) { 
                    age--; 
                } 
            } else { 
                //monthNow>monthBirth 
                age--; 
            } 
        } 

        return age; 
    }
    
	/**
     * 字符串转换成日期
     * @Title:fromString
     * @Description:
     * @param:@strDate 字符串日期格式
     * @throws
     */
	public static Date fromString(String strDate){
		DateFormat formater = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
		Date date=null;
		try {
			date=formater.parse(strDate);			
		} catch (ParseException e) {
			// TODO Auto-generated catch block	
//			logger.warn("字符串转日期中发生异常");
			e.printStackTrace();					
		}
		return date;
	}
	
    /**
     * 将指定格式的时间String转为Date类型
     * @param dateStr String 待转换的时间String
     * @param pattern String 转换的类型
     * @throws ParseException
     * @return Date
     */
    public static Date fromString ( String dateStr , String pattern )           
    {
    	try{
            if ( dateStr == null )
            {
                return null ;
            }
            SimpleDateFormat sdf = new SimpleDateFormat ( pattern ) ;
            return sdf.parse ( dateStr ) ;
    	} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return new Date();

    }
    

	/**
	 * 校验日期是否合法
	 * 
	 * @return
	 */
	public static boolean isValidDate(String s) {
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		try {
			fmt.parse(s);
			return true;
		} catch (Exception e) {
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			return false;
		}
	}
	
	 /**
     * <li>功能描述：时间相减得到天数
     * @param beginDateStr
     * @param endDateStr
     * @return
     * long 
     * @author Administrator
     */
    public static long getDaySub(String beginDateStr,String endDateStr){
        long day=0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate = null;
        Date endDate = null;
        
            try {
				beginDate = format.parse(beginDateStr);
				endDate= format.parse(endDateStr);
			} catch (ParseException e) {
				e.printStackTrace();
			}
            day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
            //System.out.println("相隔的天数="+day);
      
        return day;
    }
    /**
     * 得到n天之后的日期
     * @param days
     * @return
     */
    public static String getAfterDayDate(String days) {
    	int daysInt = Integer.parseInt(days);
    	
        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();
        
        SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdfd.format(date);
        
        return dateStr;
    }
    /**
     * 得到n天之后是周几
     * @param days
     * @return
     */
    public static String getAfterDayWeek(String days) {
    	int daysInt = Integer.parseInt(days);
    	
        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();
        
        SimpleDateFormat sdf = new SimpleDateFormat("E");
        String dateStr = sdf.format(date);
        
        return dateStr;
    }
    /**
     * 用途：以指定的格式格式化日期字符串
     * @param pattern 字符串的格式
     * @param currentDate 被格式化日期
     * @return String 已格式化的日期字符串
     * @throws NullPointerException 如果参数为空
     */
    public static String formatDate ( Date currentDate , String pattern )
    {
       
        SimpleDateFormat sdf = new SimpleDateFormat ( pattern ) ;
        return sdf.format ( currentDate ) ;
    }
    /**
     * 获取今天是星期几  7--星期日 1--星期1.....6--星期六
     */
    public static int  getWeekday(){
    	Date today = new Date();
        Calendar c=Calendar.getInstance();
        c.setTime(today);
        int weekday=c.get(Calendar.DAY_OF_WEEK);
       
        return weekday;
    }
    /**
     * 获取某时间的星期
     * @param date：日期
     * @return
     */
    public static int getWeek(Date date)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return calendar.get(Calendar.DAY_OF_WEEK);
    }
    /**
     * 获取下周星期几的日期
     * @@param 1：星期1.....7:星期日
     * @return
     */
    public static String getDayByNextWeekday(int i){
    	Date today = new Date();
    	today.setDate(today.getDate()+7);
        SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd");
    	Calendar c=Calendar.getInstance();
    	//当前时间，貌似多余，其实是为了所有可能的系统一致	
    	c.setTime(today);
    	c.set(Calendar.DAY_OF_WEEK, i);	
    	//System.out.println("周一时间:"+sdfd.format(c.getTime()));
    	return sdfd.format(c.getTime());
    }
    /**
     * 获取当前的日期
     * @@param 
     * @return
     */
    public static String getCurrentDate(String pattern){
    	Date now=new Date();
    	SimpleDateFormat sdf = new SimpleDateFormat ( pattern ) ;
        return sdf.format ( now ) ;
    }
    
    /**
     * 获取当前的年份
     * @return String
     */
    public static String getCurrentYear(){
    	Calendar c = Calendar.getInstance();
    	c.setTime(new Date());
    	Integer year=c.get(Calendar.YEAR);
    	return year.toString();
    }
    
    /**
     * 获取当前的月份
     * @return String
     */
    public static String getCurrentMonth(){
    	Calendar c = Calendar.getInstance();
    	c.setTime(new Date());
    	Integer month=c.get(Calendar.MONTH);
    	return month.toString();
    }
    
    /**
     * 获取当前的月日
     * @return String
     */
    public static String getCurrentDay(){
    	Calendar c = Calendar.getInstance();
    	c.setTime(new Date());
    	Integer month=c.get(Calendar.DAY_OF_MONTH);
    	return month.toString();
    }    

    
    /**
     * 获取当前的日期
     * @@param 
     * @return
     */
    public static String getNow(){
    	Date now=new Date();
    	SimpleDateFormat sdf = new SimpleDateFormat ( DEFAULT_DATETIME_FORMAT) ;
        return sdf.format ( now ) ;
    }
    
    /**
     * 获取当前的日期和时间
     * @param pattern 日期类型
     * @return String
     */
    public static String getNow(String pattern){
    	Date now=new Date();
    	SimpleDateFormat sdf = new SimpleDateFormat (pattern) ;
        return sdf.format ( now );
    }    
   
    
    /**
     * 获取当前的日期
     * @@param 
     * @return
     */
    public static Date getNowDate(){
    	Date now=new Date();
    	SimpleDateFormat sdf = new SimpleDateFormat ( DEFAULT_DATETIME_FORMAT) ;
        return fromString(sdf.format ( now )) ;
    }
    
    
    /**
     * 获取当前时间和日期
     * @param pattern
     * @return Date
     */
    public static Date getNowDate(String pattern){
    	Date now=new Date();
    	SimpleDateFormat sdf = new SimpleDateFormat (pattern) ;
        return fromString(sdf.format ( now ),pattern) ;
    }
    
    /**
	 * 将当前的时间进行相加减
	 * @param calendarType 加减日期的类型，如Calendar.MINUTE
	 * @param num 日期加减的数值 
	 * @return
	 */
	public static Date getDateTimeNext(int calendarType, int num){
		        
	    Calendar cl = Calendar.getInstance();	
//	    cl.setTime(DateUtil.getNowDate());
	    cl.add(calendarType, num); 
	    Date afterDate = (Date) cl.getTime(); 			
		String formatDate=formatDate(afterDate, DEFAULT_DATETIME_FORMAT);
		Date returnDate	=fromString(formatDate, DEFAULT_DATETIME_FORMAT);
        return returnDate;  
	};
	
	
	/**
	 * 将制定的时间进行相加减
	 * @param originDate 制定的时间
	 * @param calendarType calendarType 加减日期的类型，如Calendar.MINUTE
	 * @param num 日期加减的数值
	 * @return
	 */
	public static Date getDateTimeNext(Date originDate,int calendarType, int num){
        
	    Calendar cl = Calendar.getInstance();
	    cl.setTime(originDate);
	    cl.add(calendarType, num); 
		Date afterDate = (Date) cl.getTime(); 		
		String formatDate=formatDate(afterDate, DEFAULT_DATETIME_FORMAT);
		Date returnDate	=fromString(formatDate, DEFAULT_DATETIME_FORMAT);
        return returnDate;  
	};
    
}
